import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:stacked/stacked.dart';
import 'package:vista/app/di/injection.dart';
import 'package:vista/features/challenge/viewmodels/challenge_detail_viewmodel.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/utils/flash_notifier.dart';
import 'package:vista/shared/widgets/auth_gate_modal.dart';

/// 挑战详情页面
class ChallengeDetailView extends StatelessWidget {
  final String submissionId;

  const ChallengeDetailView({super.key, required this.submissionId});

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<ChallengeDetailViewModel>.reactive(
      viewModelBuilder:
          () => ChallengeDetailViewModel(
            getIt.get(),
            getIt.get<AuthFocus>(),
            getIt.get(),
            submissionId,
          )..initialize(),
      builder: (context, model, child) {
        if (model.isBusy || model.submission == null) {
          return Scaffold(
            body: Container(
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/my-background.png'),
                  fit: BoxFit.fill,
                ),
              ),
              child: const Center(child: CircularProgressIndicator()),
            ),
          );
        }

        return Scaffold(
          body: SizedBox.expand(
            child: Stack(
              children: [
                // 全屏背景图片
                _buildBackgroundImage(model.submission!.image),
                // 左上角返回按钮（带蒙层）
                _buildBackButton(context),
                // 底部蒙层（用户信息和关注按钮）
                _buildBottomOverlay(context, model),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 构建全屏背景图片
  Widget _buildBackgroundImage(String imagePath) {
    Widget imageWidget;

    // 判断是本地文件路径还是asset路径
    if (imagePath.startsWith('/') || imagePath.startsWith('file://')) {
      // 本地文件路径
      imageWidget = Image.file(
        File(imagePath),
        width: double.infinity,
        height: double.infinity,
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          return Container(
            width: double.infinity,
            height: double.infinity,
            color: Colors.grey[300],
            child: const Center(
              child: Icon(Icons.broken_image, size: 40, color: Colors.grey),
            ),
          );
        },
      );
    } else {
      // asset路径
      imageWidget = Image.asset(
        imagePath,
        width: double.infinity,
        height: double.infinity,
        fit: BoxFit.cover,
        errorBuilder: (context, error, stackTrace) {
          return Container(
            width: double.infinity,
            height: double.infinity,
            color: Colors.grey[300],
            child: const Center(
              child: Icon(Icons.broken_image, size: 40, color: Colors.grey),
            ),
          );
        },
      );
    }

    return Positioned.fill(child: imageWidget);
  }

  /// 构建左上角返回按钮（带蒙层）
  Widget _buildBackButton(BuildContext context) {
    return SafeArea(
      child: Padding(
        padding: EdgeInsets.only(left: 14.w, top: 14.h),
        child: Container(
          decoration: BoxDecoration(
            color: Colors.black.withOpacity(0.3),
            borderRadius: BorderRadius.circular(20.r),
          ),
          child: GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Padding(
              padding: EdgeInsets.all(8.w),
              child: Image.asset(
                'assets/images/back.png',
                width: 24.w,
                height: 24.w,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 构建底部蒙层（用户信息和关注按钮）
  Widget _buildBottomOverlay(
    BuildContext context,
    ChallengeDetailViewModel model,
  ) {
    if (model.author == null) {
      return const SizedBox.shrink();
    }

    final author = model.author!;

    return Positioned(
      left: 0,
      right: 0,
      bottom: 0,
      child: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Colors.transparent, Colors.black.withOpacity(0.7)],
          ),
        ),
        padding: EdgeInsets.fromLTRB(14.w, 20.h, 14.w, 40.h),
        child: SafeArea(
          child: Row(
            children: [
              // 用户头像
              Container(
                width: 56.w,
                height: 56.w,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.white,
                  border: Border.all(color: Colors.white, width: 2.w),
                  image:
                      author.avatar != null
                          ? DecorationImage(
                            image: AssetImage(author.avatar!),
                            fit: BoxFit.cover,
                          )
                          : null,
                ),
                child:
                    author.avatar == null
                        ? Icon(
                          Icons.person,
                          size: 28.w,
                          color: Colors.grey[400],
                        )
                        : null,
              ),
              SizedBox(width: 12.w),
              // 用户信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      author.username,
                      style: TextStyle(
                        fontSize: 16.sp,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
                    if (author.signature != null &&
                        author.signature!.isNotEmpty)
                      Padding(
                        padding: EdgeInsets.only(top: 4.h),
                        child: Text(
                          author.signature!,
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: Colors.white.withOpacity(0.8),
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                  ],
                ),
              ),
              // 关注按钮
              _buildFollowButton(context, model),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建关注按钮
  Widget _buildFollowButton(
    BuildContext context,
    ChallengeDetailViewModel model,
  ) {
    // 检查是否是自己
    final isSelf =
        model.currentUser != null &&
        model.author != null &&
        model.currentUser!.id == model.author!.id;

    return InkWell(
      onTap: () async {
        // 如果是自己，提示用户
        if (isSelf) {
          FlashNotifier.flashInfo('This is your own submission');
          return;
        }

        final currentUser = await getIt<AuthFocus>().getCurrentUser();
        if (currentUser == null) {
          final result = await showDialog<bool>(
            context: context,
            builder: (context) => const AuthGateModal(),
          );
          if (result == true) {
            Navigator.of(context).pushNamed('/login');
          }
          return;
        }

        await model.toggleFollow();
        if (context.mounted) {
          FlashNotifier.flashSuccess(
            model.isFollowing
                ? 'Followed successfully'
                : 'Unfollowed successfully',
          );
        }
      },
      borderRadius: BorderRadius.circular(20.r),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.h),
        decoration: BoxDecoration(
          color:
              model.isFollowing ? Colors.white.withOpacity(0.3) : Colors.white,
          borderRadius: BorderRadius.circular(20.r),
          border: Border.all(color: Colors.white, width: 1.w),
        ),
        child: FittedBox(
          fit: BoxFit.scaleDown,
          child: Text(
            model.isFollowing ? 'Following' : 'Pay attention',
            style: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.w600,
              color: model.isFollowing ? Colors.white : Colors.black87,
            ),
          ),
        ),
      ),
    );
  }
}
